package com.doumuxie.service.impl;

import com.doumuxie.common.entity.UserLoginLog;
import com.doumuxie.repository.UserLoginLogRepository;
import com.doumuxie.service.UserLoginLogService;
import com.doumuxie.util.ResultUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author doumuxie https://gitee.com/doumuxie/
 * @version 1.0
 * @date 2020/11/30 19:06
 * @description 用户登录日志
 **/
@Service
@RequiredArgsConstructor
public class UserLoginLogServiceImpl implements UserLoginLogService {

    final UserLoginLogRepository userLoginLogRepository;

    @Override
    public ResultUtil list(String userId) {
        List<UserLoginLog> all = userLoginLogRepository.findAll(new Example<UserLoginLog>() {
            @Override
            public UserLoginLog getProbe() {
                UserLoginLog userLoginLog = new UserLoginLog();
                userLoginLog.setUserId(userId);
                return userLoginLog;
            }

            @Override
            public ExampleMatcher getMatcher() {
                return ExampleMatcher.matching();
            }
        });
        return ResultUtil.success(all);
    }

    @Override
    public ResultUtil save(String userId, String ipAddress) {
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setUserId(userId);
        userLoginLog.setLoginIp(ipAddress);
        userLoginLog.setCreateTime(LocalDateTime.now());
        userLoginLog.setUpdateTime(LocalDateTime.now());
        userLoginLog.setLoginTime(LocalDateTime.now());
        UserLoginLog save = userLoginLogRepository.save(userLoginLog);
        if (StringUtils.isNotBlank(save.getId())) {
            return ResultUtil.success();
        }
        return ResultUtil.error("保存失败");
    }
}
